<script setup>
import {onMounted, ref} from "vue";
import {getGroupInfo, updateGroup} from "@/api/group.js";
import {onBeforeRouteUpdate, useRoute} from "vue-router";
import {host_custom} from "@/host.js";
import { computed } from "vue";
import {showToast} from "@/components/toasts/LoginRegToast.js";
import GroupAvatarUploadSvg from "@/components/svg/GroupAvatarUploadSvg.vue";
import emitter from "@/utils/EventBus.js";
import {Modal} from "bootstrap";

const route = useRoute()

const groupForm = ref({
  group_name: '',
  group_pic: null,
  banner: null,
  brief: ''
})
const groupManageModal = ref()
const originalBadBoi = ref({})

const hasChanges = computed(() => {
  return groupForm.value.group_name !== originalBadBoi.value.group_name ||
      groupForm.value.brief !== originalBadBoi.value.brief ||
      groupForm.value.group_pic !== originalBadBoi.value.group_pic ||
      groupForm.value.banner !== originalBadBoi.value.banner
})

const fetchGroupData = async (groupId) => {
  const res = await getGroupInfo(groupId)
  const [obj] = res.data
  groupForm.value = obj
  originalBadBoi.value = JSON.parse(JSON.stringify(obj))
}

const bannerPreview = ref()
const picPreview = ref()

const picChange = (e) => {
  const file = e.target.files[0]
  if (file.size > 1024 * 1024 * 10 ) {
    showToast('warning', '图片限制10MB')
    e.target.value = null
    return false
  } else {
    groupForm.value.group_pic = file
    picPreview.value = URL.createObjectURL(file)
  }
}

const bannerChange = e => {
  const file = e.target.files[0]
  if (file.size > 1024 * 1024 * 10 ) {
    showToast('warning', '图片限制10MB')
    e.target.value = null
    return false
  } else {
    groupForm.value.banner = file
    bannerPreview.value = URL.createObjectURL(file)
  }
}



onMounted(async () => {
  await fetchGroupData(route.params.groupId)
  groupManageModal.value = new Modal(document.getElementById('groupManageModal'))
})

const save = async () => {
  const formData = new FormData()

  if (groupForm.value.group_name !== originalBadBoi.value.group_name) {
    formData.append('group_name', groupForm.value.group_name)
  }

  if (groupForm.value.brief !== originalBadBoi.value.brief) {
    formData.append('brief', groupForm.value.brief)
  }

  if (groupForm.value.group_pic !== originalBadBoi.value.group_pic) {
    formData.append('group_pic', groupForm.value.group_pic)
  }

  if (groupForm.value.banner !== originalBadBoi.value.banner) {
    formData.append('banner', groupForm.value.banner)
  }

  formData.append('gid', route.params.groupId)

  const res = await updateGroup(formData)
  if (res.status === 200) {
    groupManageModal.value.hide()
    showToast('success', '已保存')
    emitter.emit('update group')
  }
}
onBeforeRouteUpdate(async (to, from, next) => {
  await fetchGroupData(to.params.groupId)
  next()
})
</script>

<template>
  <div class="modal fade" id="groupManageModal" tabindex="-1" aria-labelledby="groupManageModal" aria-hidden="true" data-mdb-backdrop="true" data-mdb-keyboard="true">
    <div class="modal-dialog modal-fullscreen-sm-down">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">群管理</h5>
          <button type="button" ref="closeBtn" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>

        <div class="modal-body">
         <ul class="nav nav-tabs" id="myTab" role="tablist">
           <li class="nav-item" role="presentation">
             <button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home-tab-pane" type="button" role="tab" aria-controls="home-tab-pane" aria-selected="true">群资料</button>
           </li>
           <li class="nav-item" role="presentation">
             <button class="nav-link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile-tab-pane" type="button" role="tab" aria-controls="profile-tab-pane" aria-selected="false">群成员</button>
           </li>
           <li class="nav-item" role="presentation">
             <button class="nav-link" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact-tab-pane" type="button" role="tab" aria-controls="contact-tab-pane" aria-selected="false">权限</button>
           </li>
         </ul>

          <div class="tab-content" id="myTabContent">
            <div class="tab-pane fade show active" id="home-tab-pane" role="tabpanel" aria-labelledby="home-tab" tabindex="0">
              <form id="groupManageForm">

                <div class="my-3">
                  <label for="groupName" class="form-label">群名称</label>
                  <input v-model="groupForm.group_name" type="text" class="form-control" id="groupName" placeholder="请输入群聊名称" required>
                </div>


                <div class="mb-3">
                  <label for="groupDescription" class="form-label">群介绍</label>
                  <textarea v-model="groupForm.brief" class="form-control" id="groupDescription" rows="3" placeholder="请输入群介绍"></textarea>
                </div>


                <div class="mb-3 d-flex">
                  <div class="flex-grow-1 d-flex flex-column align-items-center justify-content-center">
                    <p>更换封面</p>

                    <label for="groupBanner" style="cursor: pointer" class="form-label position-relative d-flex justify-content-center align-items-center">
                      <img
                          v-if="groupForm.banner"
                          id="bannerPreview"
                          :src="bannerPreview? bannerPreview: `${host_custom}/banner/${groupForm.banner}`"
                          alt="预览" class="img-thumbnail"
                          style="max-width: 200px; max-height: 100px;"
                      >
                      <GroupAvatarUploadSvg v-if="!groupForm.banner"/>

                      <span class="text-body-emphasis"><font-awesome-icon :icon="['fas', 'pen-to-square']" /></span>
                    </label>
                    <input @change.prevent="bannerChange" class="d-none" type="file" id="groupBanner" accept="image/*">
                    <button @click.prevent="groupForm.banner=null" v-if="groupForm.banner" class="btn btn-danger btn-sm">删除封面</button>
                  </div>

                  <div class="flex-grow-1 d-flex flex-column align-items-center justify-content-center">
                    <p>更换群图片</p>
                    <label for="grouPicPreview" style="cursor: pointer" class="form-label d-flex position-relative justify-content-center align-items-center">
                      <img
                          id="picPreview"
                          :src="picPreview? picPreview : `${host_custom}/gpfp/${groupForm.group_pic}`"
                          alt="预览"
                          class="img-thumbnail rounded-circle"
                          style="max-width: 200px; max-height: 100px;"
                      >
                      <span class="text-body-emphasis"><font-awesome-icon :icon="['fas', 'pen-to-square']" /></span>
                    </label>
                    <input @change.prevent="picChange" class="d-none" type="file" id="grouPicPreview" accept="image/*">
                  </div>
                </div>
              </form>
            </div>
           <div class="tab-pane fade" id="profile-tab-pane" role="tabpanel" aria-labelledby="profile-tab" tabindex="0">...</div>
           <div class="tab-pane fade" id="contact-tab-pane" role="tabpanel" aria-labelledby="contact-tab" tabindex="0">...</div>
          </div>


          <div class="modal-footer">
            <button type="button" ref="closeBtn" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" @click="save" :disabled="!hasChanges" id="submitGroupInfo">保存</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
#picPreview:hover, #bannerPreview:hover {
  //filter: brightness(.5);
}

label:hover img {
  filter: brightness(.7);
}

label:hover span {
  display: initial;
}


label span {
  display: none;
  position: absolute;
}
</style>